package com.zlc.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlc.common.utils.PageUtils;
import com.zlc.common.utils.Query;

import com.zlc.gulimall.product.dao.CategoryDao;
import com.zlc.gulimall.product.entity.CategoryEntity;
import com.zlc.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2.组装成父子的树形结构
        //2.1) 返回
        return listTree(entities,0);
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //todo 1.检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Transactional
    @Override
    public void updateDetails(CategoryEntity category) {
        Long catId = category.getCatId();
        this.baseMapper.updateById(category);
        if(!StringUtils.isEmpty(category.getName())){
            this.update(category,new LambdaUpdateWrapper<CategoryEntity>().eq(CategoryEntity::getCatId,catId));
        }
    }

    /*
     * 获取当前菜单的子菜单
     * */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all) {
        Long rootCatId = root.getCatId();
        List<CategoryEntity> childrens = all.stream().filter(categoryEntity -> categoryEntity.getParentCid() == rootCatId)
                .map(menu -> {
                    menu.setChildren(getChildrens(menu, all));
                    return menu;
                }).collect(Collectors.toList());
        return childrens;
    }
    /*
     * 递归组装成父子树
     * */
    private List<CategoryEntity> listTree(List<CategoryEntity> all ,int i) {
        if(++i > 3) return null;
        int ii = i;
        return all.stream().filter(categoryEntity -> categoryEntity.getCatLevel() == ii)
                .map(menu -> {
                    menu.setChildren(getChildrens(menu,all));
                    return menu;
                }).collect(Collectors.toList());
    }

}